package com.example.myactspringboot.config;

import com.example.myactspringboot.bean.SysUser;
import com.example.myactspringboot.server.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.http.parser.Authorization;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Create 2023-09-23 07:43
 * @Description
 */
public class UserReal extends AuthorizingRealm {
    @Autowired
    private SysUserService service;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.err.println("授权");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.err.println("认证");
/*        String username =  "admin";
        String password = "123";*/
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        SysUser sysUser = service.getUserByName(userToken.getUsername());
        if (sysUser==null||!userToken.getUsername().equals(sysUser.getName())){
            return null;//抛出异常UnknownAccountException
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("username",sysUser.getName());
        session.setTimeout(1800000);
        return new SimpleAuthenticationInfo("",sysUser.getPassword(),"");
    }
}
